/<template>
  <el-dialog
    :visible.sync="visible"
    title="选择任务规划模型"
    append-to-body
    width="60%"
  >
    <div class="aside">
      <el-form
        :inline="true"
        :model="formInline"
        class="demo-form-inline"
        size="small"
      >
        <el-form-item label="模型名称：">
          <el-input
            v-model="formInline.mxmc"
            v-max-length-tip="30"
            v-no-space
            placeholder="请输入模型名称"
          ></el-input>
        </el-form-item>
        <!--        <el-form-item label="模型类型：">-->
        <!--          <el-input-->
        <!--            v-model="formInline.mxlx"-->
        <!--            v-max-length-tip="30"-->
        <!--            v-no-space-->
        <!--            placeholder="请输入模型类型"-->
        <!--          ></el-input>-->
        <!--        </el-form-item>-->
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button type="primary" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      :data="tableData"
      style="width: 100%"
      stripe
      @selection-change="handleSelectionChange"
      class="mainTable"
      height="40vh"
      ref="multipleBottomTab"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="序号" type="index" width="55"> </el-table-column>
      <el-table-column show-overflow-tooltip label="模型名称" prop="mxmc">
      </el-table-column>
      <el-table-column show-overflow-tooltip label="算法名称" prop="sfmc">
      </el-table-column>
      <!-- <el-table-column show-overflow-tooltip label="基本算法" prop="jbsf">
      </el-table-column> -->
      <!-- <el-table-column show-overflow-tooltip label="元任务数量" prop="yrwsl">
      </el-table-column> -->
      <el-table-column show-overflow-tooltip label="任务完成率" prop="rwfgl">
      </el-table-column>
      <el-table-column show-overflow-tooltip label="模型类型" prop="mxlx">
      </el-table-column>

      <el-table-column
        show-overflow-tooltip
        label="观测时效性均值"
        prop="gcsxxjz"
      >
      </el-table-column>
      <el-table-column show-overflow-tooltip label="侧摆角均值" prop="cbjjz">
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        label="太阳高度角均值"
        prop="tygdjjz"
      >
      </el-table-column>
      <el-table-column show-overflow-tooltip label="版本信息" prop="bbxx">
      </el-table-column>
    </el-table>
    <div class="fl_row_start">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="pageCurrent"
        :page-size="pageSize"
        layout="prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleconfirmChkeck">确定</el-button>
      <el-button @click="cancelJcmxDialog">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { CallGenerateTaskScheme } from '@/api/decisionManage/index.js'
import { getRwghmxPageApi } from '@/views/modelManagement/missionPlanning/api'
import { convertNullsToZeros } from '@/utils/index'

export default {
  props: {
    callback: {
      type: Function,
      default: () => {}
    }
  },
  data() {
    return {
      tableData: [],
      visible: false,
      formInline: {
        mxmc: '',
        mxlx: ''
      },
      pageCurrent: 1,
      pageSize: 10,
      total: 0,
      paramsForm: [], // 用于元任务列表的数据
      multipleSelection: [], // 用于选择模型列表的数据
      loadingFull: null,
      automatic: false,
      tjTime: '',
      resultTjTime: ''
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.getJcmxPageData(this.formInline) // 获取模型列表
      }
    }
  },
  mounted() {
    this.$bus.$on('openFooterModal', bool => {
      this.visible = bool // 打开模型选择弹窗
      this.automatic = this.visible // 代表着是自动化
    })
  },
  methods: {
    // 弹窗点击确定方法
    handleconfirmChkeck() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择模型')
        return
      }
      if (this.automatic == true) {
        // 存储所选的规划模型
        localStorage.setItem('ghmx', this.multipleSelection[0].mxid)
        this.$bus.$emit('showAutomationMask', true)
        this.$bus.$emit('saveAutoConfig', true)
      } else {
        this.handleSave()
      }
      this.visible = false
    },

    // 调用分批处理的接口
    sendDataToBackend(dataChunk) {
      return CallGenerateTaskScheme(dataChunk).then(response => {
        this.resultTjTime = response.data.data
      })
    },

    // 分批处理数据
    async sendAllDataInOrder(dataArray = [], chunkSize = 80) {
      const promises = []
      for (let i = 0; i < dataArray.length; i += chunkSize) {
        let dataChunk = dataArray.slice(i, i + chunkSize)
        const localId = JSON.parse(localStorage.getItem('ghmx'))

        const params = {
          mxID: localId != null ? localId : this.multipleSelection[0].mxid,
          znjcJsonStr: JSON.stringify(dataChunk).replace(/\"/g, "'"),
          tjTime: this.tjTime
        }
        promises.push(this.sendDataToBackend(params))
      }
      await Promise.all(promises)
      if (this.automatic) {
        this.$bus.$emit('closeAutomationMask')
      }
      if (!this.automatic) {
        this.loadingFull.close()
      }
      localStorage.setItem(
        'yrwbh',
        this.paramsForm.map(item => item.yrwbh).join(',')
      )
      localStorage.removeItem('ghmx')
      this.$router.push({
        path: '/business-management/assessment',
        query: {
          tjTime: this.tjTime,
          flag: this.automatic
        }
      })
    },

    // 调用接口
    handleSave() {
      // 将null转为0
      this.paramsForm = convertNullsToZeros(this.paramsForm)

      // 如果选择大于80，则调用分批处理
      if (this.paramsForm.length > 80) {
        if (this.automatic !== true) {
          this.loadingFull = this.$loading({
            lock: true,
            text: '正在进行任务规划',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
        } else {
          // 继续显示loading
          this.$bus.$emit('showAutomationMask', true)
        }
        this.tjTime = new Date().getTime() // 生成时间戳，以便于分辨分发的接口数据属于哪一块
        return this.sendAllDataInOrder(this.paramsForm)
      } else {
        // 自动化已经有弹窗了，所以不需要在创建一个弹窗
        if (this.automatic !== true) {
          this.loadingFull = this.$loading({
            lock: true,
            text: '正在进行任务规划',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
        } else {
          // 同理
          this.$bus.$emit('showAutomationMask', true)
        }
        let params = {}
        // 如果点击的是自动化，就从本地读取
        if (this.automatic) {
          const localId = JSON.parse(localStorage.getItem('ghmx'))
          params = {
            mxID: localId != null ? localId : this.multipleSelection[0].mxid,
            znjcJsonStr: JSON.stringify(this.paramsForm).replace(/\"/g, "'"),
            tjTime: new Date().getTime()
          }
        } else {
          // 双引号转为单引号
          const znjcJsonStr = JSON.stringify(this.paramsForm).replace(
            /\"/g,
            "'"
          )
          params = {
            mxID: this.multipleSelection[0].mxid, // 如果本地有则代表点击自动化
            znjcJsonStr: znjcJsonStr,
            tjTime: new Date().getTime() // 传递给后端一个时间戳，用于区分不同的接口数据
          }
        }

        CallGenerateTaskScheme(params).then(response => {
          if (response.data.code !== 200) {
            this.$message.error(response.data.message)
            return
          }

          this.resultTjTime = response.data.data // 存储发给后端的时间戳

          this.$message.success(
            response.data.message != null
              ? response.data.message
              : '生成任务方案成功'
          )
          // 手动操作需要关闭loading弹窗
          if (this.automatic !== true) {
            this.loadingFull.close()
          }

          // 关闭模型弹窗
          this.cancelJcmxDialog()
          // 如果是自动化操作，则关闭自动化弹窗
          if (this.automatic) {
            this.$bus.$emit('closeAutomationMask')
          }
          // 将yrwbh存储到localStorage中
          localStorage.setItem(
            'yrwbh',
            this.paramsForm.map(item => item.yrwbh).join(',')
          )
          localStorage.removeItem('ghmx')
          // 跳转到评估页面，传递tjTime和flag参数
          this.$router.push({
            path: '/business-management/assessment',
            query: {
              tjTime: this.resultTjTime,
              flag: this.automatic !== true ? false : true
            }
          })
        })
      }
    },

    // 关闭弹窗
    cancelJcmxDialog() {
      this.$refs.multipleBottomTab.clearSelection()
      this.visible = false
    },

    // 获取表格数据
    getJcmxPageData(data) {
      const query = {
        ...data,
        pageCurrent: this.pageCurrent,
        pageSize: this.pageSize
      }
      getRwghmxPageApi(query).then(res => {
        if (res.data.code === 200) {
          const data = res.data
          this.tableData = data.data.records
          this.total = data.data.total
          // if (this.automatic) {
          //   this.multipleSelection = [this.tableData[0]] // 自动化，自动选择第一个模型，套一个数组避免报错
          //   this.handleSave(this.automatic) // 调用模型选择
          // }
        }
      })
    },

    // 打开弹窗
    openModal(value, flag) {
      if (this.automatic) {
        this.paramsForm = value // 这是在元列表中选择的数据
        this.handleSave()
      } else {
        this.visible = true
        this.paramsForm = value // 这是在元列表中选择的数据
        this.automatic = flag == true ? true : false
        this.getJcmxPageData(this.formInline) // 获取模型列表
      }

      // 关闭loading，让用户选择模型
      // if (this.automatic) {
      // this.$bus.$emit('closeAutomationMask', false)
      // }
    },
    // 重置模型列表
    onReset() {
      this.pageCurrent = 1
      this.formInline = {}
      this.getJcmxPageData(this.formInline)
    },

    // 查询模型列表
    onSubmit() {
      this.pageCurrent = 1
      this.getJcmxPageData(this.formInline)
    },

    // 勾选回调方法
    handleSelectionChange(val) {
      this.multipleSelection = val // 可以将选中项保存到data中的某个属性，便于后续使用

      // 如果选中项数组长度大于1，则只保留最后一个选中项
      if (val.length > 1) {
        // 取消选中之前所有项
        val.forEach(key => {
          if (key !== val[val.length - 1]) {
            // 保留最后一个选中项
            this.$refs.multipleBottomTab.toggleRowSelection(key, false)
          }
        })

        // 注意：在Element UI的某些版本中，上面的循环可能不足以完全取消选中，
        // 因为toggleRowSelection可能在内部进行了优化。此时，可以直接设置选中项数组
        this.$refs.multipleBottomTab.clearSelection() // 清除所有选中项（如果需要）
        this.$refs.multipleBottomTab.toggleRowSelection(
          val[val.length - 1],
          true
        ) // 仅选中最后一个项
      }
    },

    // 分页回调方法
    handleSizeChange(val) {
      this.pageSize = val
      this.getJcmxPageData(this.formInline)
    },

    // 页码回调方法
    handleCurrentChange(val) {
      this.pageCurrent = val
      this.getJcmxPageData(this.formInline)
    }
  }
}
</script>

<style scoped>
::v-deep .el-table .el-table__header-wrapper .el-table__header th .el-checkbox {
  display: none;
}
</style>
